package jmath.io.data;

import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.XYDataset;
import java.util.*;
import org.springframework.util.*;

public class JMathXYDataset extends AbstractXYDataset implements XYDataset {

	private class XYPare<T extends Number> {
		private T x;

		private T y;

		public XYPare(T x, T y) {
			this.x = x;
			this.y = y;
		}

		public T getX() {
			return x;
		}

		public T getY() {
			return y;
		}
	}

	private Map<Integer, List<XYPare<Double>>> dataMap = new HashMap<Integer, List<XYPare<Double>>>();

	private Map<Integer, String> nameMap = new HashMap<Integer, String>();

	private int currentSeria = -1;

	public JMathXYDataset() {		
	}

	public Number getX(int i, int j) {
		return dataMap.get(i).get(j).getX();
	}

	public Number getY(int i, int j) {
		return dataMap.get(i).get(j).getY();
	}

	public int getSeriesCount() {
		return dataMap.size();
	}

	public Comparable getSeriesKey(int i) {
		String name = nameMap.get(i);
		if (name != null) {
			return name;
		} else {
			return "";
		}
	}

	public int getItemCount(int i) {
		return dataMap.get(i).size();
	}
	

	public void createNewSeria(String name) {
		currentSeria = currentSeria + 1;
		nameMap.put(currentSeria, name);
		dataMap.put(currentSeria, new ArrayList<XYPare<Double>>());
	}

	public void addNewDot(double x, double y) {
		List<XYPare<Double>> data=dataMap.get(currentSeria);
		Assert.notNull(data);
		data.add(new XYPare<Double>(x, y));
	}

	public void viewData() {
		notifyListeners(new DatasetChangeEvent(this, this));
	}

	public void clearData() {
		dataMap.clear();
		nameMap.clear();
		currentSeria = -1;		
	}
	
	public void clearData(String name) {
		for(Integer seriaNumber:nameMap.keySet()){
			if(nameMap.get(seriaNumber).equals(name)){
				nameMap.remove(seriaNumber);
				dataMap.remove(seriaNumber);
				if(seriaNumber==currentSeria){
					currentSeria = currentSeria-1;
				}
			}
		}						
	}
	
}
